import React, { Component } from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as surveyAction from '../../actions/survey.action';
import Charts from '../plugins/Charts';
import { Select } from 'sq-ui';
import moment from 'moment';
import style from './style';
import { Modal, DateSelect } from '../../ui-components';
import cx from 'classnames';
import { Link, SearchInput, Loading, tip } from 'sq-ui';
import { hashHistory } from 'react-router'
import util from '../../util';
import { findDOMNode } from 'react-dom';

export default
@connect(({ survey }) => ({ survey }), dispatch => ({actions: bindActionCreators({ ...surveyAction }, dispatch)}))
class SurveyChart extends Component {

  static contextTypes = {
    router: React.PropTypes.object,
  };

  historyTimeState = {
    from: +moment().month(-4),
    to: +moment(),
  };

  state = {
    activities: null,
    activeActivity: null,
    historyItems: null,
    disable: true,
    checkAll: false,
    checkAllItem: null,
    check_all_search: '',
    ...this.historyTimeState,
  };

  handleCheckAllSearch = (e) => {
    const { value } = e.target;
    util.throttle(() => {
      this.setState({
        check_all_search: value,
      });
    });
  };

  handleSelect = (value) => {
    this.setState({
      disable: true,
    });
    hashHistory.push({
      pathname: this.props.location.pathname,
      query: {
        ...this.props.location.query,
        activeActivity: value,
      }
    });
  };

  handleTab = (tab) => {
    if (this.state.disable) return;
    let query = {};
    if (tab === 2) {
      this.setState({
        items: null,
        activities: null,
        activeActivity: null,
        disable: true,
        ...this.historyTimeState,
      });
      this.activityPageNumber = 1;
      query = {
        tab,
      };
    } else {
      this.setState({
        historyItems: null,
        disable: true,
      });
      query = {
        tab,
        activeActivity: this.props.location.query.activeActivity,
      };
    }

    hashHistory.push({
      pathname: this.props.location.pathname,
      query,
    });
  };

  activityPageNumber = 1;

  componentWillMount() {
    if (this.props.location.query.tab === undefined) {
      hashHistory.push({
        pathname: this.props.location.pathname,
        query: {
          ...this.props.location.query,
          tab: 1
        }
      });
    } else {
      if (this.props.location.query.tab == 1) {
        if (!this.props.location.query.activeActivity) {
          this.props.actions.fetchSurveyActivities(this.activityPageNumber, (res) => {
            this.setState({
              activities: res.data,
            });
            if (util.isNull(res.data)) {
              this.setState({
                disable: false,
              });
              return;
            }
            hashHistory.push({
              pathname: this.props.location.pathname,
              query: {
                ...this.props.location.query,
                activeActivity: res.data[0].surveyActivityId,
              }
            });
          });
        } else {
          this.props.actions.fetchSurveyActivities(this.activityPageNumber, (res) => {
            this.setState({
              activities: res.data,
            });
          });
          this.fetchItems();
        }
      } else {
        this.fetchHistory();
      }
    }
  }

  componentWillReceiveProps(props) {
    const { tab, activeActivity } = props.location.query;
    const { tab: prevTab, activeActivity: prevActiveActivity } = this.props.location.query;

    if (tab != prevTab) {
      if (tab == 1) {
        this.props.actions.fetchSurveyActivities(this.activityPageNumber, (res) => {
          this.setState({
            activities: res.data,
          });

          if (!activeActivity) {
            if (util.isNull(res.data)) {
              this.setState({
                disable: false,
              });
              return;
            }
            hashHistory.push({
              pathname: props.location.pathname,
              query: {
                ...props.location.query,
                activeActivity: res.data[0].surveyActivityId,
              }
            });
          } else {
            this.fetchItems(props);
          }
        });
      } else {
        this.fetchHistory(props);
      }
    }

    else if (activeActivity !== prevActiveActivity && tab ==1) {
      this.fetchItems(props);
    }
  }

  fetchItems = (props) => {
    const id = (props || this.props).location.query.activeActivity;
    this.setState({
      items: null,
      disable: true,
    });
    this.props.actions.fetchSurveyActivityItems(id, (res) => {
      this.setState({
        items: res.data.surveyItemVOs,
        disable: false,
      });
    });
  };

  fetchHistory = (startTime, endTime) => {
    this.setState({
      historyItems: null,
      disable: true,
    });

    let f = startTime;
    let t = endTime;
    if (!f || !t) {
      f = this.state.from;
      t = this.state.to;
    }

    //暂时去掉此接口，已经没用了20180131
     this.props.actions.fetchSurveyHistoryItems(f, t, (res) => {
       this.setState({
         historyItems: res.data,
        disable: false,
       });
     });
  };

  renderHistory() {
    return (
      <div>
        <div style={{padding: '25px 25px 0 25px'}}>
          <div style={{marginBottom: '5px'}}>生效时间</div>
          <div className={style['date-select']}>
            <DateSelect
              disabled={this.state.disable}
              time={this.state.from && (moment(+this.state.from).format('YYYY-MM-DD'))}
              onChange={value => {
                this.setState({
                  from: value,
                });
                if (this.state.to) {
                  this.fetchHistory(value, this.state.to);
                }
              }}
            />
            <span>
            到
            </span>
            <DateSelect
              disabled={this.state.disable}
              time={this.state.to && (moment(+this.state.to).format('YYYY-MM-DD'))}
              onChange={value => {
                this.setState({
                  to: value,
                });
                if (this.state.from) {
                  this.fetchHistory(this.state.from, value);
                }
              }}
            />
          </div>
        </div>
        {
          this.state.historyItems ? this.state.historyItems.map((item) => {
            if (item.surveyItemVO.surveyItemType == 1) {
              return (
                <Charts 
                  width={960}
                  height={400}
                  data={item.surveyActivityVOs.reverse()}
                  title={item.surveyItemVO.question}
                  type={'line'}
                  series={[
                    {
                      name:'平均分',
                      value: function(item){return item.averageScore},
                    }
                  ]}
                  tooltip={{
                    trigger:'axis',
                    enterable: 'true',
                    position: function (point, params, dom) {
                      return [point[0], '20%'];
                    },
                    formatter: (v) => {
                      return `<div style="font-size: 12px;padding: 10px;"><div>${moment(v[0].data.item.createdTime).format('YYYY年MM月DD日')}发送</div><div>收到问卷：${v[0].data.item.totalResponseNumber}份</div><div>平均分：${v[0].value}</div><a style="color: #1AA9F1; font-size: 12px;" href="/charts/#/e/survey?tab=1&activeActivity=${v[0].data.item.surveyActivityId}">查看详情></a></div>`;
                    },
                  }}
                  xAxis={{
                    boundaryGap : false,
                    type: 'category',
                    name: '时间',
                    value: function (item) {return moment(item.createdTime).format('YYYY-MM-DD')}
                  }}
                  yAxis={{
                    name: '平均分',
                    type: 'value',
                    max: 10,
                  }}
                />
              );
            }
            // 两项回答
            else if (item.surveyItemVO.surveyItemType == 2) {
              return (
                <Charts 
                  width={960}
                  height={400}
                  data={item.surveyActivityVOs.reverse()}
                  title={item.surveyItemVO.question}
                  type={'line'}
                  series={[
                    {
                      name:'肯定回答比例',
                      value: function(item){return item.percentage},
                    }
                  ]}
                  tooltip={{
                    trigger:'axis',
                    enterable: 'true',
                    position: function (point, params, dom) {
                      return [point[0], '20%'];
                    },
                    formatter: (v) => {
                      return `<div style="font-size: 12px;padding: 10px;"><div>${moment(v[0].data.item.createdTime).format('YYYY年MM月DD日')}发送</div><div>收到问卷：${v[0].data.item.totalResponseNumber}份</div><div>肯定回答比例：${v[0].data.value}%</div><a style="color: #1AA9F1;font-size: 12px;" href="/charts/#/e/survey?tab=1&activeActivity=${v[0].data.item.surveyActivityId}">查看详情></a></div>`;
                    },
                  }}
                  xAxis={{
                    boundaryGap : false,
                    type: 'category',
                    name: '时间',
                    value: function (item) {return moment(item.createdTime).format('YYYY-MM-DD')}
                  }}
                  yAxis={{
                    name: '百分比',
                    type: 'value',
                    max: 100,
                    axisLabel: {
                      formatter: '{value} %'
                    }
                  }}
                />
              );
            }
            else {
              return (
                <Charts 
                  width={960}
                  height={400}
                  data={item.surveyActivityVOs.reverse()}
                  title={item.surveyItemVO.question}
                  type={'line'}
                  series={[
                    {
                      name:'问卷数量',
                      value: function(item){return item.totalResponseNumber},
                    }
                  ]}
                  tooltip={{
                    trigger:'axis',
                    enterable: 'true',
                    position: function (point, params, dom) {
                      return [point[0], '20%'];
                    },
                    formatter: (v) => {
                      return `<div style="font-size: 12px;padding: 10px;"><div>${moment(v[0].data.item.createdTime).format('YYYY年MM月DD日')}发送</div><div>收到问卷：${v[0].data.item.totalResponseNumber}份</div><div>肯定回答比例：${v[0].data.value}%</div><a style="font-size: 12px;color: #1AA9F1;" href="/charts/#/e/survey?tab=1&activeActivity=${v[0].data.item.surveyActivityId}">查看详情></a></div>`;
                    },
                  }}
                  xAxis={{
                    boundaryGap : false,
                    type: 'category',
                    name: '时间',
                    value: function (item) {return moment(item.createdTime).format('YYYY-MM-DD')}
                  }}
                  yAxis={{
                    name: '问卷数量',
                    type: 'value',
                  }}
                />
              );
            }
          }) : <Loading small style={{marginLeft: '25px'}}/>
        }
        {
          (this.state.historyItems && !this.state.historyItems.legnth) ? (
            <div style={{padding: '10px 25px'}}>没有数据.</div>
          ) : null
        }
      </div>
    );
  }

  renderItems() {
    return (
      <div>
        {
          !util.isNull(this.state.activities) ?
            <div style={{padding: '25px'}} className={style['select-wrapper']}>
              <span style={{float: 'left', marginRight: '5px'}}>调研发送时间: </span>
              <Select
                disabled={this.state.disable}
                onChange={this.handleSelect}
                id="surveyActivityId"
                value={this.props.location.query.activeActivity}
                item={
                  (item, i) => {
                    return (
                      <li
                        data-value={item.surveyActivityId}
                        key={i}
                      >
                        {moment(item.createdTime).format('YYYY年MM月DD日')}
                      </li>
                      );
                  }
                }
                list={this.state.activities}
                className={style.select}
              />
            </div>
            : <div style={{height: '25px'}}></div>
        }
        {
          ((this.state.items && !this.state.items.length) || (this.state.activities && !this.state.activities.length)) && <div style={{padding: '0px 25px 10px 25px'}}>没有数据</div>
        }
        {
          this.state.items ? this.state.items.map((item, i) => {
            if (item.surveyItemType == 1 || item.surveyItemType == 2) {
              return (
                <div key={i} className={style.item}>
                  {
                    item.surveyItemType == 1 ?
                    <Charts
                      key={i}
                      width={600}
                      height={470}
                      title={item.question}
                      type="bar"
                      series={[
                        {
                          name:'人数',
                          value: function(item){
                            return item.value
                          },
                        }
                      ]}
                      tooltip={{
                        trigger:'axis',
                      }}
                      data={item.surveyChartVOs}
                      xAxis={{
                        type: 'category',
                        name: '分数',
                        value: function (item) {return item.key - 3 + '分'}
                      }}
                      yAxis={{
                        name: '人数',
                        type: 'value',
                      }}
                    /> : 
                    <Charts 
                      width={600}
                      height={500}
                      data={[item.surveyChartVOs.map(v => v.value)]}
                      title={item.question}
                      type={'pie'}
                      series={[
                        {
                          name: item.lowLabel,
                          value: function(item){
                            return item[0]
                          },
                        },{
                          name: item.highLabel,
                          value: function(item){return item[1]},
                        }
                      ]}
                      tooltip={{
                        trigger:'item',
                      }}
                    />
                  }
                  <div>
                    <div className={style['item-response']}>
                      <ul>
                        {
                          item.surveyResponseVOs.slice(0, 3).map((v, i) => (
                            <li key={i}>{v.responseDetail}</li>
                          ))
                        }
                        {
                          item.surveyResponseVOs.length > 3 ? (
                            <li className={style['check-all']} onClick={() => this.setState({checkAll: true, checkAllItem: item})}>查看全部</li>
                          ) : null
                        }
                      </ul>
                    </div>
                    <div className={style['item-cloud']}>
                      <Charts 
                        width={428}
                        height={186}
                        data={item.surveyTagVOs.map(v => ({
                          name: v.name,
                          value: v.weight,
                        }))}
                        type={'wordCloud'}
                        series={{
                          gridSize: 20,
                          sizeRange: [12, 50],
                          value: item.surveyTagVOs.map(v => ({
                            name: v.name,
                            value: v.weight,
                          }))
                        }}
                        tooltip={{
                          trigger:'item',
                        }}
                        onClick={(_item) => {
                          this.setState({
                            checkAll: true,
                            checkAllItem: item,
                            check_all_search: _item.name,
                          }, () => {
                            findDOMNode(this.refs.checkAllInput.refs.input).value = _item.name;
                          });
                        }}
                      />
                    </div>
                  </div>
                </div>
              );
            }
            else return (
              <div key={i} className={style.item}>
                <div className={style['cloud-wrapper']}>
                  <div style={{
                    color: '#000',
                    fontSize: '18px',
                    fontWeight: 'bold',
                    marginTop: '-8px',
                    marginLeft: '20px'
                  }}>{item.question}</div>
                  <div className={style['item-cloud']} style={{height: '182px', width: '578px'}}>
                    <Charts 
                      width={576}
                      height={178}
                      data={item.surveyTagVOs.map(v => ({
                        name: v.name,
                        value: v.weight,
                      }))}
                      type={'wordCloud'}
                      series={{
                        gridSize: 20,
                        sizeRange: [12, 50],
                        value: item.surveyTagVOs.map(v => ({
                          name: v.name,
                          value: v.weight,
                        }))
                      }}
                      tooltip={{
                        trigger:'item',
                      }}
                      onClick={(_item) => {
                        this.setState({
                          checkAll: true,
                          checkAllItem: item,
                          check_all_search: _item.name,
                        }, () => {
                          findDOMNode(this.refs.checkAllInput.refs.input).value = _item.name;
                        });
                      }}
                    />
                  </div>
                </div>
                <div className={style['item-response']}>
                  <ul>
                    {
                      item.surveyResponseVOs.slice(0, 3).map((v, i) => (
                        <li key={i}>{v.responseDetail}</li>
                        ))
                    }
                    {
                      item.surveyResponseVOs.length > 3 ? (
                        <li className={style['check-all']} onClick={() => this.setState({checkAll: true, checkAllItem: item})}>查看全部</li>
                        ) : null
                    }
                  </ul>
                </div>
              </div>
            );
          }) : null
        }
        {
          (!this.state.items && (!util.isNull(this.state.activities))) ? <Loading small style={{marginLeft: '25px'}}/>: null
        }
      </div>
    );
  }

  render() {
    return (
      <div className={style.root}>
        <header>匿名调研看板</header>
        <section className={style.body}>
          <ul className={cx(style.tabs, {
            [style.disable]: this.state.disable
          })}>
            <li onClick={this.handleTab.bind(null,1)} className={cx({ [style.active]: this.props.location.query.tab == 1 })}>看板首页</li>
            <li onClick={this.handleTab.bind(null, 2)} className={cx({ [style.active]: this.props.location.query.tab == 2 })}>历史记录</li>
          </ul>
          <div>
            {
              this.props.location.query.tab == 1 ? (
                this.renderItems()
              ) : null
            }
             {
              (this.props.location.query.tab == 2) ? (
                this.renderHistory()
              ) : null
            }
          </div>
        </section>
        <Modal
          active={this.state.checkAll}
          onRequestClose={() => this.setState({ checkAll: false }, () => {
            setTimeout(() => {
              this.setState({
                checkAllItem: null,
                check_all_search: '',
              });
            }, 300);
          })}
          close
          title="调研文字反馈列表"
          className={style['check-all-modal']}
        >
          {
            this.state.checkAllItem ?
            <div className={style['check-all']}>
              <div><span style={{color: '#3E90DD', display: 'inline-block', marginRight: '10px'}}>相关问题</span> {this.state.checkAllItem.question}</div>
              <div><span  style={{color: '#3E90DD', display: 'inline-block', marginRight: '10px'}}>调研发送时间</span> {moment(this.state.checkAllItem.createdTime).format('YYYY年MM月DD日')}</div>
              <SearchInput
                ref="checkAllInput"
                style={{margin: '10px 0'}}
                onChange={this.handleCheckAllSearch}
              />
              <ul>
                {
                  this.state.checkAllItem.surveyResponseVOs.filter(v => {
                    const { check_all_search } = this.state;
                    if (!check_all_search.trim()) return true;
                    return ~v.responseDetail.indexOf(check_all_search);
                  }).map((v, i) => {
                    const label = v.response < 14 ? v.response - 3 : v.response == 14 ? 'Y': 'N';
                    return (
                      <li key={i}>
                        <span>{v.responseDetail}</span>
                        <Link
                          top
                          style={{float: 'right', color: '#CBD2E1', fontSize: '24px', marginRight: '16px', marginTop: '-5px' }}
                          label={label} tip={`所填选项：${label === 'Y' ? this.state.checkAllItem.lowLabel : label === 'N' ? this.state.checkAllItem.highLabel : (label + '分')}`}
                        />
                      </li>
                    );
                  })
                }
              </ul>
            </div>
            : null
          }
        </Modal>
      </div>
    );
  }
}
